#include "ConfigFile.h"
#include "StringConverter.h"

#include <fstream>

ConfigFile::ConfigFile(const std::string& filename) : _filename(filename), _separators("=:\t")
{
}


ConfigFile::~ConfigFile(void)
{
}

bool ConfigFile::parse()
{
	if ( _keys.empty())	{	_keys.clear();	}

	std::ifstream file;
	file.open(_filename.c_str());
	if (file.bad()) 
	{ 
		file.close(); 
		return false; 
	}

	std::string line;
	while ( !file.eof() )
	{
		std::getline(file, line, '\n');
		std::string::size_type strip = line.find_last_not_of(" \t\n\r");
		if ( strip != std::string::npos ) { line.substr(0, strip + 1);  }

		std::string::size_type separatorPos = line.find_first_of(_separators, 0);
		if ( separatorPos != std::string::npos ) 
		{ 
			std::string key = line.substr(0, separatorPos); 
			std::string::size_type nonSeparator = line.find_first_not_of(_separators, separatorPos);
			if (nonSeparator != std::string::npos)
			{
				_keys[key] = line.substr(nonSeparator);
			}
		}
	}

	file.close();
	return true;
}

void ConfigFile::save()
{
	if (_keys.empty()) { return; }

	std::map<std::string, std::string>::iterator it;
	std::ofstream file(_filename.c_str());

	for(it = _keys.begin(); it != _keys.end(); it++)
	{
		file << it->first << '=' << it->second << std::endl;
	}

	file.close();
}

bool ConfigFile::doesKeyExist(const std::string& key)
{
	if (!_keys.empty())
	{
		std::map<std::string, std::string>::iterator it = _keys.find(key);
		if (it != _keys.end()) { return true; }
	}
	return false;
}

void ConfigFile::setKey(const std::string& key, const std::string& value)
{
	_keys[key] = value;
}

std::string ConfigFile::getAsString(const std::string& key)
{
	std::string value;

	if ( _keys.empty() ) { return ""; }

	std::map<std::string, std::string>::iterator it = _keys.find(key);
	if ( it != _keys.end() ) { value = it->second; }

	return value;
}

bool ConfigFile::getAsBool(const std::string& key)
{
	return StringConverter::convertToBool( getAsString(key) );
}

int ConfigFile::getAsInt(const std::string& key)
{
	return StringConverter::convertToInt( getAsString(key) );
}

float ConfigFile::getAsFloat(const std::string& key)
{
	return StringConverter::convertToFloat( getAsString(key) );
}

std::vector<std::string> ConfigFile::getAsStringVector(const std::string& key)
{
	std::vector<std::string> list;

	if ( !_keys.empty())
	{
		list = StringConverter::convertToStringVector( getAsString(key) );
	}

	return list;
}